//
//  ClusterChatWindowController.m
//  HiQ
//
//  Created by arvintan on 12-8-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ClusterChatWindowController.h"
#import "MainWindowController.h"
#import "ImageAndTextCell.h"
#import "FileAssistant.h"
#import "Buddy.h"

@interface ClusterChatWindowController ()

@end

@implementation ClusterChatWindowController


@synthesize isShow;

@synthesize clusterChatSource;
@synthesize tableClusterMember;

@synthesize textChatMsg;
@synthesize textSendMsg;
@synthesize buttonSendMsg;

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        chatMessage = @"";
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [[[MainWindowController sharedMainWindowController] clusterChatArray] addObject:self];
        //[nc addObserver:self selector:@selector(clusterChatWindowWillClose:) name:NSWindowWillCloseNotification object:self.window];
        [nc addObserver:self selector:@selector(changeBackgroundImage:) name:ChangeBackgroundImageNotification object:nil];
    }
    
    return self;
}

- (void)windowWillClose:(NSNotification *)notification
{
    //将聊天记录数据写入文件
    if (![chatMessage isEqualToString:@""]) {
        [FileAssistant saveData:chatMessage selfQQ:[NSString stringWithFormat:@"%li",((Buddy*)[MainWindowController shareMyselfInfo]).buddyQQ] fileName:[NSString stringWithFormat:@"%li",[clusterChatSource _cluster]->clusterId]];
    }
    [[[MainWindowController sharedMainWindowController] clusterChatArray] removeObject:self];
}


-(void) initClusterChat:(Cluster *)cluster
{
    clusterChatSource = [[ClusterChatSource alloc] initWithCluster:cluster];
    clusterChatSource._delegate =self;
    [clusterChatSource onGetClusterMember];
}

- (void) awakeFromNib
{    
    NSTableColumn* column = [tableClusterMember tableColumnWithIdentifier:@"ClusterMember"];
	
	ImageAndTextCell* cell = [[ImageAndTextCell alloc] init];
	[column setDataCell: cell];
    
    [tableClusterMember setDataSource:clusterChatSource];
    [tableClusterMember setDelegate:(id<NSTableViewDelegate>)self];
    [tableClusterMember setAction:@selector(onClickClusterMember:)];
    [tableClusterMember setDoubleAction:@selector(onDoubleClickClusterMember:)]; 
    
    [textChatMsg setFont:[NSFont fontWithName:@"华文楷体" size:16]];
}

-(void) getMemberList
{
    [self RefreshMemberList];
    [tableClusterMember reloadData];
}

- (void) RefreshMemberList
{
    Cluster *cluster = [clusterChatSource _cluster];
    NSMutableArray *memberList = [cluster memberList];
    NSInteger end = [memberList count] -1;
    NSInteger start = 0;
    while(start <= end) {
        NSInteger online = -1;
        NSInteger offline = end + 1;
        //正序查找不在线的
        for (NSInteger i = start; i<=end; i++) {
            Buddy *b = [memberList objectAtIndex:i];
            if (b.status != BUDDY_STATUS_ONLINE) {
                offline = i;
                break;
            }
        }
        //倒序查找在线的
        for (NSInteger j = end; j>offline; j--) {
            Buddy *end_b = [memberList objectAtIndex:j];
            if (end_b.status == BUDDY_STATUS_ONLINE) {
                online = j;
                break;
            }
        }            
        if ((offline<=end)&&(online>=0)) {
            //交换位置
            [memberList exchangeObjectAtIndex:offline withObjectAtIndex:online];
        }
        //更新搜索位置
        start = offline + 1;
        end = online - 1;
    }   
    for (NSUInteger i = 0 ; i < [memberList count]; ++i) {
        if ([[memberList objectAtIndex:i] buddyQQ] == [[MainWindowController shareMyselfInfo] buddyQQ] && i != 0) {
            [memberList exchangeObjectAtIndex:0 withObjectAtIndex:i];
            return;
        }
    }
}

-(BOOL) tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    return NO;
}

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
    if (rowIndex < [[[clusterChatSource _cluster] memberList] count] ) {
        if([[aTableColumn identifier] isEqualToString:@"ClusterMember"])
        {
            //NSLog(@"%ld",rowIndex);
            Buddy *buddy = [[[clusterChatSource _cluster] memberList] objectAtIndex:rowIndex];
           // NSLog(@"%ld",buddy.buddyQQ);
            NSColor *txtColor;
            if (buddy->status == BUDDY_STATUS_ONLINE)
            {
                [(ImageAndTextCell*)aCell setImage: buddy->onPhoto];
                txtColor = [NSColor blackColor];
            }
            else
            {
                [(ImageAndTextCell*)aCell setImage: buddy->offPhoto];
                //字体为灰
                txtColor = [NSColor colorWithDeviceRed:(161/255.0) green:(161/255.0) blue:(161/255.0) alpha:1.0];
            }
            [(ImageAndTextCell*)aCell setStringValue:buddy->buddyName];
            
            NSFont *txtFont = [NSFont boldSystemFontOfSize:13];
            NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                     txtFont, NSFontAttributeName, txtColor, NSForegroundColorAttributeName, nil];
            NSAttributedString *attrStr = [[NSAttributedString alloc]
                                           initWithString:buddy->buddyName attributes:txtDict];
            [(ImageAndTextCell*)aCell setAttributedStringValue:attrStr];
        }
    }
    else {
        NSLog(@"_cluster memberList index error ---%ld",rowIndex);
    }

}


-(void) onClickClusterMember:(id) sender
{
    
}

-(void) onDoubleClickClusterMember:(id) sender
{
    // 双击好友，打开聊天窗口
    NSUInteger row = [sender clickedRow];
    if (row == -1 || row == 0) {
        return;
    }
    Buddy *selectedItem = [[[clusterChatSource _cluster] memberList] objectAtIndex:row];
    if(selectedItem == nil)
        return;
    
    NSMutableArray *pairChatArray = [[MainWindowController sharedMainWindowController] pairChatArray];
    for (NSUInteger i = 0; i < [pairChatArray count]; ++i) {
        if ([selectedItem buddyQQ] == [[[pairChatArray objectAtIndex:i] peerBuddy] buddyQQ]) {
            [[MainWindowController sharedMainWindowController] showChatWindow:i];
            return;
        }
    }
    
    [[MainWindowController sharedMainWindowController] openPairChatWindow:selectedItem];
    for (NSUInteger i = 0; i < [pairChatArray count]; ++i) {
        if ([selectedItem buddyQQ] == [[[pairChatArray objectAtIndex:i] peerBuddy] buddyQQ]) {
            [[MainWindowController sharedMainWindowController] showChatWindow:i];
            return;            
        }
    }
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

- (void) setNamePohtoAndBgImage:(NSString*)bgImageName
{
    [clusterName setStringValue:[[clusterChatSource _cluster] clusterName]];
    [clusterPhoto setImage:[NSImage imageNamed:[clusterChatSource _cluster].photo]];
    
    [[self window]setTitle:[NSString stringWithFormat:@"%@",[[clusterChatSource _cluster] clusterName]]];
    if (bgImageName != @"NIL") {
        [textChatMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [textSendMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [self.window setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [tableClusterMember setBackgroundImage:[NSImage imageNamed:bgImageName]];
    }
    else
    {
        [textChatMsg setBackgroundColor:[NSColor  whiteColor]];
        [textSendMsg setBackgroundColor:[NSColor  whiteColor]];
        [self.window setBackgroundColor:[NSColor  whiteColor]];
        [tableClusterMember clearBackgroundImage];
    }
}

-(IBAction)sendChatMsg:(id)sender
{
    NSString *msg = [textSendMsg stringValue];
    if (![msg isEqualToString:@""]) {
        [clusterChatSource onSendChatMsg:msg Name:[[MainWindowController shareMyselfInfo] buddyName]];
        [self displayChatMessage:msg Name:[[MainWindowController shareMyselfInfo] buddyName]];
        [textSendMsg setStringValue:@""];
    }
}

-(void) displayChatMessage:(NSString *)message Name:(NSString*)name
{
    NSString * msg = [[NSString alloc]init];
    if (message != nil) {
        msg = [NSString stringWithFormat:@"%@\n", message];
        // 获取当前时间的字符串
        NSString *time = [[NSDate date] stringWithFormat:@"HH:mm:ss"];
        NSString *displayName = [[NSString alloc]init];
        displayName = name;
        
        NSString *title = [NSString stringWithFormat:@"%@:  %@\n",displayName,time];
        NSLog(@" >> %@", msg);
        
        chatMessage = [NSString stringWithFormat:@"%@%@%@", chatMessage,title, msg];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [textChatMsg setString:chatMessage];
        NSRange range = [chatMessage rangeOfString:msg options:NSBackwardsSearch];
        [textChatMsg scrollRangeToVisible:range];
    });
}

-(void) changeBackgroundImage:(NSNotification*)notification
{
    NSString *bgImageName = [[notification userInfo] objectForKey:@"img"];
    NSText *text = [self.window fieldEditor:YES forObject:self];
    if (bgImageName != @"NIL") {
        //取出背景图片
        [textChatMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [textSendMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [self.window setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [tableClusterMember setBackgroundImage:[NSImage imageNamed:bgImageName]];
        [text setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [text setDrawsBackground:YES];
    }
    else
    {
        [textChatMsg setBackgroundColor:[NSColor  whiteColor]];
        [textSendMsg setBackgroundColor:[NSColor  whiteColor]];
        [tableClusterMember clearBackgroundImage];
        [self.window setBackgroundColor:[NSColor  whiteColor]];
        [text setBackgroundColor:[NSColor  whiteColor]];
        [text setDrawsBackground:YES];
    }
}

#pragma view history msg
//查看历史聊天记录
- (IBAction)viewMsgHistory:(id)sender
{
    if (((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController == nil) {
        ((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController = [[MsgHistoryWindowController alloc] initWithWindowNibName:@"MsgHistoryWindowController"];
    }
    [((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController showWindow:nil];
    [((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController initContact:[clusterChatSource _cluster]];
}


@end
